<template>
  <div>
    <el-affix :offset="40">
      <el-page-header
        icon="el-icon-arrow-left"
        @click="goTo(route.query.redirect)"
        content="我的发票"
      >
      </el-page-header>
    </el-affix>
    <el-affix :offset="40">
      <el-row>
        <el-col :span="24" style="text-align: right" v-if="invNum">
          <el-button type="primary" :size="'mini'" @click="DeleteNow()"
            >立即删除</el-button
          ><el-button
            type="primary"
            :size="'mini'"
            v-loading="downloadloading"
            @click="
              DownloadInvDetail((state) => {
                downloadloading = state;
              })
            "
            >导出表格</el-button
          ><el-button
            type="primary"
            :size="'mini'"
            @click="showRenameDialog = true"
            >重命名</el-button
          >
        </el-col>
      </el-row></el-affix
    >
    <el-table
      border
      :data="invList"
      :size="'mini'"
      v-loading="onLoadData && invList.length === 0"
      :row-class-name="tableRowClassName"
      max-height="winHeight"
      style="width: 100%"
      id="invTable"
    >
      <el-table-column type="index" width="50" />
      <el-table-column prop="fileName" label="文件名" sortable />
      <el-table-column prop="invCode" label="发票代码" sortable />
      <el-table-column prop="invNum" label="发票号码" sortable />
      <el-table-column prop="invDate" label="开票日期" sortable />
      <el-table-column prop="invMoney" label="开具金额" sortable />
      <el-table-column prop="invChk" label="验证码" width="180" sortable />
      <el-table-column prop="invTip" label="备注" sortable />
      <el-table-column label="发票详情" width="100">
        <template #default="scope">
          <div v-loading="scope.row.loading">
            <el-button
              @click="viewDetail(scope.row)"
              type="text"
              size="small"
              v-if="scope.row.invTip === '全票面解析成功'"
              >查看详情</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-loading="onLoadData" description="到底了~"></el-empty>
    <!--发票详情查看-->
    <el-dialog
      title="发票详情"
      v-model="showInvDetail"
      :width="isMobile() ? '100%' : '60%'"
    >
      <el-table :data="invDetail" stripe border id="invDetailTable">
        <el-table-column property="key" label="字段" sortable />
        <el-table-column property="value" label="值" sortable fixed="right" />
      </el-table>
    </el-dialog>
    <el-dialog
      title="重命名发票"
      v-model="showRenameDialog"
      :width="isMobile() ? '100%' : '60%'"
    >
      <el-input v-model="RenameDemoRule" disabled placeholder="规则示例...">
        <template #prepend>重命名规则</template>
      </el-input>
      <el-input v-model="RenameDemoStr" disabled placeholder="重命名示例...">
        <template #prepend>重命名示例</template>
      </el-input>

      <el-alert
        title="编辑重命名规则：在下面按钮中依次选择元素和连接符！"
        type="info"
        show-icon
      />
      <el-row class="mb-4">
        <el-button
          type="primary"
          round
          v-for="item in RenameFieldOptions"
          :key="item.value"
          @click="OnSelect(item)"
          >{{ item.label }}</el-button
        >
      </el-row>
      <el-row class="mb-4">
        <el-button
          type="warning"
          circle
          v-for="item in RenameFieldOperations"
          :key="item.value"
          @click="OnSelect(item)"
          >{{ item.label }}</el-button
        >
      </el-row>
      <el-button type="primary" @click="ClearRenameDemo()" v-if="RenameDemoStr"
        >清空</el-button
      >
      <el-button
        type="primary"
        v-loading="rename_downloading"
        @click="RenameDownload()"
        >重命名并下载</el-button
      >
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { reactive, ref, watch, onMounted, toRefs } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import { isMobile, goTo } from "@/libs/utils";
import { GetInvNum, GetInvDataBatch } from "@/libs/data";
import {
  DownloadAsExcelFile,
  DownloadImageBatch,
  DownloadInvDetail,
} from "@/libs/download";
import { ApiDeleteInvList, RenameDownloadUrl } from "@/http/api";

export default {
  setup() {
    const route = useRoute();
    const store = useStore();
    let { invNum, invList } = toRefs(store.state);
    const winHeight = ref(window.innerHeight);
    const onLoadData = ref(true);
    const invDetail = reactive([]);
    const InvCaptureUrl = ref(null);
    const showInvDetail = ref(false);
    const showInvCapture = ref(false);
    const downloadloading = ref(false);
    const rename_downloading = ref(false);
    const RenameDemoStr = ref("");
    const RenameDemoRule = ref("");
    const showRenameDialog = ref(false);
    const RenameFieldOptions = reactive([
      { label: "发票代码", value: "012002100611" },
      { label: "发票号码", value: "61271541" },
      { label: "开票日期", value: "20220701" },
      { label: "开票日期(中文)", value: "2022年07月01日" },
      { label: "金额", value: "78.12" },
      { label: "金额(含税)", value: "78.12" },
      { label: "用户名(指定)", value: "yourname" },
    ]);
    const RenameFieldOperations = reactive([
      { label: "-", value: "-" },
      { label: "_", value: "_" },
      { label: "+", value: "+" },
      { label: "=", value: "=" },
      { label: "&", value: "&" },
      { label: "|", value: "|" },
      { label: ".", value: "." },
    ]);
    //不包含在显示列表中的字段
    const exceptKeys = [
      "invCode",
      "invNum",
      "invDate",
      "invChk",
      "invMoney",
      "invTip",
      "url",
      "status",
      "code",
      "loading",
    ];
    onMounted(() => {
      //获取发票数量
      GetInvNum((state) => {
        onLoadData.value = state;
      });
      //if (invNum) ElNotification.warning("发票数据仅保留24h，请尽快下载!!!");
    });
    watch(invNum, () => {
      GetInvDataBatch((state) => {
        onLoadData.value = state;
      });
    });
    //查看发票信息
    const viewDetail = (row) => {
      if (invDetail.length > 0) {
        invDetail.length = 0;
      }
      for (let keyval in row) {
        if (exceptKeys.indexOf(keyval) === -1) {
          //只有不排除的字段才会加入
          invDetail.push({ key: keyval, value: row[keyval] });
        }
      }
      showInvDetail.value = true;
    };
    //表格状态更新
    const tableRowClassName = ({ row }) => {
      let rowClass;
      if (row.status && row.invTip === "查验成功") {
        rowClass = "success";
      } else if (row.status && row.invTip.indexOf("解析成功") !== -1) {
        rowClass = "warning";
      } else {
        rowClass = "failed";
      }
      return rowClass;
    };
    //立即删除用户数据
    const DeleteNow = () => {
      ElMessageBox.confirm("确定删除所有发票数据吗?", "Warning", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        ApiDeleteInvList().then((res) => {
          if (res.code === 2000) {
            ElMessage.success(`已删除${res.data.num0}条发票数据!`);
            store.commit("clearInvList");
          } else {
            ElMessage.error(res.message);
          }
        });
      });
    };
    //选择重命名元素
    const OnSelect = (item) => {
      if (item.label === "用户名(指定)") {
        ElMessageBox.prompt("请输入用户名", "Tip", {
          confirmButtonText: "OK",
          inputErrorMessage: "未支持的格式！",
        })
          .then(({ value }) => {
            RenameDemoStr.value += value;
            RenameDemoRule.value += value;
          })
          .catch(() => {
            //nothing
          });
      } else {
        RenameDemoStr.value += item.value;
        RenameDemoRule.value += item.label;
      }
    };
    const ClearRenameDemo = () => {
      RenameDemoRule.value = "";
      RenameDemoStr.value = "";
    };
    //重命名下载
    const RenameDownload = () => {
      if (RenameDemoRule.value === "") {
        ElMessage.warning("规则不能为空！");
        return;
      }
      rename_downloading.value = true;
      axios({
        method: "GET",
        url: RenameDownloadUrl,
        params: { rename_rule: RenameDemoRule.value },
        headers: { token: store.state.token },
        responseType: "blob",
      })
        .then((res) => {
          const link = document.createElement("a"); // 创建元素
          let blob = new Blob([res.data], { type: "application/x-tar" });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob); // 创建下载的链接
          link.setAttribute("download", "invoice_files.tar"); // 给下载后的文件命名
          document.body.appendChild(link);
          link.click(); // 点击下载
          document.body.removeChild(link); //  下载完成移除元素
          window.URL.revokeObjectURL(link.href); // 释放掉blob对象
          rename_downloading.value = false;
        })
        .catch((err) => {
          console.error(err.message);
          ElMessage.error("下载错误，请联系管理员！");
          rename_downloading.value = false;
        });
    };
    return {
      winHeight,
      onLoadData,
      downloadloading,
      invDetail,
      InvCaptureUrl,
      invList,
      invNum,
      showInvDetail,
      showInvCapture,
      isMobile,
      tableRowClassName,
      DownloadAsExcelFile,
      DownloadImageBatch,
      DownloadInvDetail,
      viewDetail,
      goTo,
      route,
      DeleteNow,
      showRenameDialog,
      RenameFieldOptions,
      RenameFieldOperations,
      RenameDemoStr,
      RenameDemoRule,
      OnSelect,
      ClearRenameDemo,
      RenameDownload,
      rename_downloading,
    };
  },
};
</script>

<style>
.el-table .failed {
  background: oldlace;
  color: #f56c6c;
}
.el-table .warning {
  background: #f0ffff;
  color: cornflowerblue;
}
.el-table .success {
  background: #f0f9eb;
  color: #67c23a;
}
.mb-4 {
  margin-top: 20px;
  margin-left: 10px;
}
</style>
